def test(fn):
= [1,1,1,2,2,3]
nums = 2
k = [1,2]
expected = fn(nums,k)
actual assert actual == expected
= [1]
nums = 1
k = [1]
expected = fn(nums,k)
actual assert actual == expected
Problem Source: Leetcode
Problem Description
Given an integer array nums
and an integer k
, return the k
most frequent elements. You may return the answer in any order.
tests
Solution
- Time Complexity:
O(n)
- Space Complexity:
O(n)
from typing import List
def topKFrequent(nums: List[int], k: int) -> List[int]:
= {}
hashmap for num in nums:
# Get a hashmap of counts for each item in num
= 1 + hashmap.get(num,0)
hashmap[num]
= [[] for _ in range(len(nums)+1)]
buckets for key,val in hashmap.items():
# Put nums in a list where index location == occurances
buckets[val].append(key)
= []
output for i in range(len(buckets) - 1, 0, -1):
# Loop through buckets backward and append to output
for num in buckets[i]:
output.append(num)if len(output) == k:
# When you have k nums you are done
return output
test(topKFrequent)